/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cfcoding.props;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tristan
 */
public class Props {

    private static Props instance = null;
    private static Properties props = new Properties();
    private static final String CONFIG_FILE = "config.properties";
    private static boolean configExists = false;

    protected Props(String filename) throws IOException {
        File config = new File(filename);
        configExists = config.exists();
        if (!configExists) {
            config.createNewFile();
        }

        loadProperties();
    }

    public static Props getInstance() {
        if (instance == null) {
            try {
                instance = new Props(CONFIG_FILE);
            } catch (IOException ex) {
                Logger.getLogger(Props.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return instance;
    }
    
    
    public String getValue (String key, String defaultVal) {
       return props.getProperty(key, defaultVal);        
    }
    
    public void setValue (String key, String val) {
        props.setProperty(key, val);
        save();
    }
    
    public boolean configSetup () {
        return configExists;
    }
    
    private void save () {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(CONFIG_FILE);
            props.store(out, null);
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(Props.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(Props.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        loadProperties();
    }
    
    private void loadProperties () {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(CONFIG_FILE));
            props.load(in);
        } catch (Exception e) {
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(Props.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
